import secrets

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials



#本项目是为了实现快速表单开发，使用json文件替代数据库table
#类似于快速实现web版的excel表格，目前还有些问题，，最大列数限制,无法分页，无法导入等等，逐步慢慢优化解决吧。
#使用方法 python3 -m uvicorn 本程序文件名:app --host '0.0.0.0' --port 85 --reload
from starlette.requests import Request
from fastapi import FastAPI,Form
from starlette.templating import Jinja2Templates
from starlette.responses import HTMLResponse
from starlette.responses import RedirectResponse
from starlette.staticfiles import StaticFiles
from fastapi import FastAPI, File, UploadFile
import time
import os,sys
import json
import datetime
from typing import List


print('start here')

print('end here')

def log(content):
    
    today=str(datetime.datetime.today())[:19]
    today0=today[:10]
    with open('logs/'+today0+'.log','a+',encoding='utf-8') as f:
        f.write(today+' '+str(content)+'\r\n')

def readjson(json_file,table='main'):
    '''读取json文件成，返回字典，如不存在，就创建json文件'''
    demo_json='''
    {
        "name": "Cactus",
        "age": 20
    }
    '''
    if json_file=='demo1.json':
        return 'demo1.json'
    if os.path.exists(json_file):
        with open(json_file, mode='r', encoding='utf-8') as f:
            data = json.load(f)
    else:
        with open(json_file, mode='w', encoding='utf-8') as ff:
            print("文件创建成功！")
            data={}
            data['main']={}
        x=json.dumps(data,indent=4,ensure_ascii=False)
        with open(json_file, 'w', encoding="utf-8") as f:
            f.write(x)
    return data
    #print(data['age'])
    

#写json
def writejson(argv,json_file,table='main'):
    '''以当前时间为key，追加写入json文件，第一个参数是要写入的内容，第二个参数是要追加写入的json文件'''
    if json_file=='demo1.json':
        return 'demo1.json'
    now = int(time.time())
    timeArray = time.localtime(now)
    now0 = time.strftime("%Y-%m-%d_%H%M%S", timeArray)

    if os.path.exists(json_file):
        with open(json_file, 'r', encoding="utf-8",) as f:
            data = json.load(f)

        #print(data['age'])
    else:
        with open(json_file, mode='w', encoding='utf-8') as ff:
            print("文件创建成功！")
            data={}
    #data['age']=20
    if table in data.keys():
        pass
    else:
        data[table]={}
    data[table][now0]=argv


    x=json.dumps(data,indent=4,ensure_ascii=False)
    with open(json_file, 'w', encoding="utf-8") as f:
        f.write(x)

        
def savejson(x,json_file):
    '''固化字典为json文件，多用于删除或修改字典后'''
    x1=json.dumps(x,indent=4,ensure_ascii=False)
    with open(json_file, 'w', encoding="utf-8") as f:
        f.write(x1)

app = FastAPI()


security = HTTPBasic()


def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = secrets.compare_digest(credentials.username, "admin")
    correct_password = secrets.compare_digest(credentials.password, "admin")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username


@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
    return {"username": username}
@app.get("/users1/me")
def read_current_user1(username: str = Depends(get_current_username)):
    return {"username": username}

#static用于存放静态文件， jsons用于存放json表格
app.mount('/jsons', StaticFiles(directory='./jsons'), name='jsons') 
app.mount('/static', StaticFiles(directory='static'), name='static')
#app.mount('/layui', StaticFiles(directory='layui'), name='layui') 

#html0这里是每个项目的首页，通过{} format字符串格式化的方式把参数传递进来
html0='''
<html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title></title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
  
<body>
<h1>{Title}</h1>
<p align="right">{logon_user}</p>
分页显示<a href="pages?p=1">1 </a><a href="pages?p=2">2 </a><a href="pages?p=3">3 </a><a href="pages?p=4">4 </a><a href="pages?p=5">5 </a><a href="pages?p=6">6 </a><a href="pages?p=7">7 </a><a href="pages?p=8">8 </a><a href="pages?p=9">9 </a><a href="pages?p=10">10 </a><a href="pages?p=11">11 </a><a href="pages?p=12">12 </a><a href="pages?p=13">13 </a><a href="pages?p=14">14 </a><a href="showall">All </a>

{action}

<table border="0" class="layui-table">
  <colgroup>
  </colgroup>
  <thead>
  <tr>
    <th>ID</th>
    {cols}

    
  </tr>
  </thead>
  <tbody>
  <br>{tables}</br>
  </tbody>
</table>

<br><input class="layui-btn layui-btn-normal" name='action' type="submit" value="{buttonname}">
{del0}
{add0}

<input type="submit" class="layui-btn" name="action"  value="查询"/>



</br>
{download1}



</body>
</html>
'''

#新增条目时需要的网页内容， 后续有精力时可以考虑把这个和首页合并成一个
addnew0='''
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title></title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
</head>
<body>
<h1>{Title}</h1>
<form  class="layui-form" name="input" action={action1} method="get"> 
 
<table border="0" class="layui-table">
  <colgroup>
  </colgroup>
  <thead>
  <tr>
    {cols}
  </tr>
  </thead>
  <tr>
    {inputs}
  </tr>

</table>
<br><input  class="layui-btn layui-btn-normal" type="submit"  value="确认提交"></br>

</form>
<a href="import">批量导入</a>
</body>
</html>
'''


#创建表单的页面， 需要输入表单名和最多10个列名
homepage='''
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title></title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
</head>
<body>
<h1>自动创建表单（最大10列）</h1>
<form  class="layui-form" name="input" action="/create" method="get"> 
<td><input class="layui-input" type="text" name="tablename" placeholder="请输入要创建的表单的英文名称"'></td>
<td><input class="layui-input" type="text" name="col1" placeholder='第1列名称'></td>
<td><input class="layui-input" type="text" name="col2" placeholder='第2列名称'></td>
<td><input class="layui-input" type="text" name="col3" placeholder='第3列名称'></td>
<td><input class="layui-input" type="text" name="col4" placeholder='第4列名称'></td>
<td><input class="layui-input" type="text" name="col5" placeholder='第5列名称'></td>
<td><input class="layui-input" type="text" name="col6" placeholder='第6列名称'></td>
<td><input class="layui-input" type="text" name="col7" placeholder='第7列名称'></td>
<td><input class="layui-input" type="text" name="col8" placeholder='第8列名称'></td>
<td><input class="layui-input" type="text" name="col9" placeholder='第9列名称'></td>
<td><input class="layui-input" type="text" name="col10" placeholder='第10列名称'></td>
<br><input  class="layui-btn layui-btn-normal" type="submit" value="确认提交"></br>
</form>
</body>
</html>
'''
@app.get("/")
def home(username: str = Depends(get_current_username)):
    
    return HTMLResponse(content=homepage)
@app.get("/create")
def create(tablename:str=None,col1:str=None,col2:str=None,col3:str=None,col4:str=None,col5:str=None,col6:str=None,col7:str=None,col8:str=None,col9:str=None,col10:str=None):
    list0=[col1,col2,col3,col4,col5,col6,col7,col8,col9,col10]
    list1=list(filter(None,list0))
    
    json_file='./jsons/'+tablename+'.json'
    x0=readjson(json_file)
    writejson(list1,json_file,table='cols')
    x0=readjson(json_file)
    print('0000000000000000000000000000000')
    print('x0',x0)
    print("x0['cols']",x0['cols'])
    list2=x0['cols']
    for x in list2:
        list3=list2[x]
    Tables(tablename,list3)
    return RedirectResponse(url='/'+tablename)

class Tables:
    

   
    
    def __init__(self,name,cols):
        self.name = name
        tablename=self.name
        cols=cols

         #读取json
        json_file='./jsons/'+tablename+'.json'
        namex=''
        for i in range(1,len(cols)+1):
            namex=namex+'<td><input class="layui-input" type="text" name="col'+str(i)+'" value=""></td>'
        @app.get("/"+self.name)
        def root1(username: str = Depends(get_current_username)):
            return RedirectResponse(url='/'+tablename+'/pages')
            
        @app.get("/"+self.name+'/pages')
        #@app.get("/pages")
        def root_pages(username: str = Depends(get_current_username),p:str=1):
            x0=readjson(json_file)
            print('!!!!!!!!!!!!!')
            print(x0,type(x0))
            colsx=[]
            for x in cols:
                colsx.append('<td>'+x+'</td>')
            colsx=''.join(colsx)

            line0='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>               
            </tr>
          '''
            line00='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
            '''
            line01='<td>{}</td>'*len(cols)
            line02='</tr>'
            line0=line00+line01+line02

            line1=[]
            y0=x0['main']
            keys=y0.keys()
            keys0=list(keys)
            len0=len(keys0)
            
            for key in keys0[len0-50*int(p):len0-50*(int(p)-1)]:
                #if key=='cols':
                #    continue
                line1.append(line0.format(key,y0[key]['col1'],y0[key]['col2'],y0[key]['col3'],y0[key]['col4'],y0[key]['col5'],y0[key]['col6'],y0[key]['col7'],y0[key]['col8'],y0[key]['col9'],y0[key]['col10']))
            #line1=line1[:len(colsx)]
            line1.sort(reverse=True)
            print('line1:',line1)
            #return RedirectResponse(url='/login/who')
            #return {'hello':'world'}
            return HTMLResponse(content=html0.format(cols=colsx,Title='当前所有条目',action='<form name="input" action=/'+tablename+'/action method="get">',tables=''.join(line1), buttonname="修改",download='download',test='test',del0='<input type="submit" class="layui-btn layui-btn-danger" name="action" value="删除"/>',add0='<input type="submit" class="layui-btn layui-btn-warm" name="action" value="新增"/>',download1='<a href="/jsons/'+tablename+'.json">Json文件下载x</a>',logon_user=username))
        
        
        @app.get('/'+tablename+'/addnew')
        def addnew(username: str = Depends(get_current_username)):
            cols0=''
            for x in cols:
                cols0=cols0+'<td>'+x+'</td>'

                
            return HTMLResponse(content=addnew0.format(Title='新增条目',cols=cols0,inputs=namex,action1="./addnew1?col1=*&col2=*&col3=*&col4=*&col5=*"))
        
        #根目录，指向login模块
        @app.get("/"+self.name+'/showall')
        #@app.get("/")
        def showall(username: str = Depends(get_current_username)):
            x0=readjson(json_file)
            print('!!!!!!!!!!!!!')
            print(x0,type(x0))
            colsx=[]
            for x in cols:
                colsx.append('<td>'+x+'</td>')
            colsx=''.join(colsx)

            line0='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>               
            </tr>
          '''
            line00='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
            '''
            line01='<td>{}</td>'*len(cols)
            line02='</tr>'
            line0=line00+line01+line02

            line1=[]
            y0=x0['main']
            for key in y0:
                #if key=='cols':
                #    continue
                line1.append(line0.format(key,y0[key]['col1'],y0[key]['col2'],y0[key]['col3'],y0[key]['col4'],y0[key]['col5'],y0[key]['col6'],y0[key]['col7'],y0[key]['col8'],y0[key]['col9'],y0[key]['col10']))
            #line1=line1[:len(colsx)]
            line1.sort(reverse=True)
            print('line1:',line1)
            #return RedirectResponse(url='/login/who')
            #return {'hello':'world'}
            return HTMLResponse(content=html0.format(cols=colsx,Title='当前所有条目',action='<form name="input" action=/'+tablename+'/action method="get">',tables=''.join(line1), buttonname="修改",download='download',test='test',del0='<input type="submit" class="layui-btn layui-btn-danger" name="action" value="删除"/>',add0='<input type="submit" class="layui-btn layui-btn-warm" name="action" value="新增"/>',download1='<a href="/jsons/'+tablename+'.json">Json文件下载x</a>',logon_user=username))
        
        @app.get('/'+tablename+'/addnew')
        def addnew(username: str = Depends(get_current_username)):
            cols0=''
            for x in cols:
                cols0=cols0+'<td>'+x+'</td>'

                
            return HTMLResponse(content=addnew0.format(Title='新增条目',cols=cols0,inputs=namex,action1="./addnew1?col1=*&col2=*&col3=*&col4=*&col5=*"))
        
        
        @app.get('/'+tablename+'/query')
        def query(username: str = Depends(get_current_username)):
            cols0=''
            for x in cols:
                cols0=cols0+'<td>'+x+'</td>'

                
            return HTMLResponse(content=addnew0.format(Title='查询',cols=cols0,inputs=namex,action1="./query1?col1=*&col2=*&col3=*&col4=*&col5=*"))
        
        @app.get('/'+tablename+'/query1')
        def query1(username: str = Depends(get_current_username),col1:str='',col2:str='',col3:str='',col4:str='',col5:str='',col6:str='',col7:str='',col8:str='',col9:str='',col10:str=''):
            c=(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10)
            x,y=c.index(max(c)),max(c)
            str0='col'+str(x+1)
            x0=readjson(json_file)
            y0=x0['main']
            listx=[]
            for key in y0:
                print(key)
                if y0[key][str0]==y:
                    print('same',y0[key][str0])
                    listx.append(key)
            

            print(listx)    
            #x0=readjson(json_file)
            print('!!!!!!!!!!!!!')
            print(x0,type(x0))
            colsx=[]
            for x in cols:
                colsx.append('<td>'+x+'</td>')
            colsx=''.join(colsx)

            line0='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>               
            </tr>
          '''
            line00='''
            <tr>
                <td><label><input name="Created_Date" type="radio" value={}></label></td>
            '''
            line01='<td>{}</td>'*len(cols)
            line02='</tr>'
            line0=line00+line01+line02

            line1=[]
            print(listx)
            for key in y0:
                if key in listx:
                    print('key:',key)
                    str0=line0.format(key,y0[key]['col1'],y0[key]['col2'],y0[key]['col3'],y0[key]['col4'],y0[key]['col5'],y0[key]['col6'],y0[key]['col7'],y0[key]['col8'],y0[key]['col9'],y0[key]['col10'])
                    print(str0)
                    line1.append(str0)
            #line1=line1[:len(colsx)]
            print('line1:',line1)
            #return RedirectResponse(url='/login/who')
            #return {'hello':'world'}
            return HTMLResponse(content=html0.format(cols=colsx,Title='查询结果'+y,action='<form name="input" action=/'+tablename+'/action method="get">',tables=''.join(line1), buttonname="修改",download='download',test='test',del0='<input type="submit" class="layui-btn layui-btn-danger" name="action" value="删除"/>',add0='<input type="submit" class="layui-btn" name="action" value="新增"/>',download1='<a href="/jsons/'+tablename+'.json">Json文件下载x</a>'))
        
        
        @app.get('/'+tablename+'/action')
        def action(username: str = Depends(get_current_username),Created_Date:str=None,col1:str=None,col2:str=None,col3:str=None,col4:str=None,col5:str=None,action:str=None):
            if action=='新增':
                return RedirectResponse(url='/'+tablename+'/addnew')
            elif action=='删除':
                confirm='''
                <html>
                <body>
                <h2>{}</h2>
                <a href={}>确定删除</a>                  <a href={}>不删除，返回</a>
                </body>
                </html>
                '''
                url='/'+tablename+'/delete?Created_Date='+Created_Date
                url_back='/'+tablename
                return HTMLResponse(content=confirm.format('确定删除？',url,url_back)) 
                
                print('url:',url)
                return RedirectResponse(url=url)
            elif action=='修改':
                
                url='/'+tablename+'/modify?Created_Date='+Created_Date
                print('url:',url)
                return RedirectResponse(url=url)
            elif action=='查询':
                return RedirectResponse(url='/'+tablename+'/query')
        
        @app.get('/'+tablename+'/addnew1')
        def addnew1(username: str = Depends(get_current_username),col1:str=None,col2:str=None,col3:str=None,col4:str=None,col5:str=None,col6:str=None,col7:str=None,col8:str=None,col9:str=None,col10:str=None):
            dictx={}
            dictx['col1']=col1
            dictx['col2']=col2
            dictx['col3']=col3
            dictx['col4']=col4
            dictx['col5']=col5
            dictx['col6']=col6
            dictx['col7']=col7
            dictx['col8']=col8
            dictx['col9']=col9
            dictx['col10']=col10
            writejson(dictx,json_file)
            log(tablename+' '+username+' '+'addnew '+str(dictx))
            return RedirectResponse(url='/'+tablename)
        
        @app.get('/'+tablename+'/delete')
        def delete0(username: str = Depends(get_current_username),Created_Date:str=None):
            #print('delete here..........')
            #x=Created_Date
            #print('x',x)
            #return Created_Date
            x0=readjson(json_file)
            log(tablename+' '+username+' '+'del '+str(x0['main'][Created_Date]))
            del x0['main'][Created_Date]
            print(x0)
            savejson(x0,json_file)
            return RedirectResponse(url='/'+tablename)
        @app.get('/'+tablename+'/import')
        def import0(username: str = Depends(get_current_username),Data:str=None):
            import1='''
            <html>
            <body>
                <form action="import2" name="ok" method="post">
               
                   <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">批量导入，从excel表复制过来粘贴，不包含表头，每行需要耗时1秒钟</label>
                        <div class="layui-input-block">
                          <textarea placeholder="请输入内容" name=fname1 class="layui-textarea"></textarea>
                        </div>
                      </div>
                      <input type="submit" value="Submit" />
                </form>
            </body>
            </html>
            '''
            return HTMLResponse(content=import1)
        
        
        @app.post('/'+tablename+'/import2')
        def import2(username: str = Depends(get_current_username),fname1:str=Form(...)):
            fname=fname1
            print(fname,type(fname))
            list_x=fname.replace('\r','').split('\n')
            for item in list_x:
                if item=='':
                    continue
                
                newlist=item.split('\t')
                list1=newlist
                list2=','.join(list1+['']*(10-len(list1))).split(',')
                col1,col2,col3,col4,col5,col6,col7,col8,col9,col10=list2
                dictx={}
                dictx['col1']=col1
                dictx['col2']=col2
                dictx['col3']=col3
                dictx['col4']=col4
                dictx['col5']=col5
                dictx['col6']=col6
                dictx['col7']=col7
                dictx['col8']=col8
                dictx['col9']=col9
                dictx['col10']=col10
                writejson(dictx,json_file)
                log(tablename+' '+username+' '+'addnew '+str(dictx))
                time.sleep(1)

            html_x0='''
            <html>
            <body>
            <a href={url}>完成，请返回</a>
            </body>
            </html>
            '''    
            return HTMLResponse(content=html_x0.format(url='/'+tablename))

        @app.get('/'+tablename+'/modify')
        def modify(username: str = Depends(get_current_username),Created_Date:str=None,col1:str =None,col2:str =None,col3:str=None,col4:str=None,col5:str=None,col6:str=None,col7:str=None,col8:str=None,col9:str=None,col10:str=None,action:str=None):
            if Created_Date==None:
                #return RedirectResponse(url='/'+tablename)
                return 'hello'
            elif action==None:
                colsx=[]
                for x in cols:
                    colsx.append('<td>'+x+'</td>')
                colsx=''.join(colsx)
                print("UUUUUUUUUUUUUUUUUUU")
                x0=readjson(json_file)
                print('!!!!!!!!!!!!!')
                print(x0,type(x0))

                line0='''
                <tr>
                <td><label><input name="Created_Date" type="radio" value={} checked="checked"></label></td>
                    <td><input class="layui-input" type="text" name="col1" value={}></td>
                    <td><input class="layui-input" type="text" name="col2" value={}></td>
                    <td><input class="layui-input" type="text" name="col3" value={}></td>
                    <td><input class="layui-input" type="text" name="col4" value={} ></td>
                    <td><input class="layui-input" type="text" name="col5" value={} ></td>
                    <td><input class="layui-input" type="text" name="col6" value={}></td>
                    <td><input class="layui-input" type="text" name="col7" value={}></td>
                    <td><input class="layui-input" type="text" name="col8" value={}></td>
                    <td><input class="layui-input" type="text" name="col9" value={} ></td>
                    <td><input class="layui-input" type="text" name="col10" value={} ></td>
                </tr>
              '''
                line00='''
                                <tr>
                <td><label><input name="Created_Date" type="radio" value={} checked="checked"></label></td>
                '''
                line01=''
                for i in range(1,len(cols)+1):
                    line01=line01+'<td><input class="layui-input" type="text" name="col'+str(i)+'" value={}></td>'
                line02='</tr>'
                line0=line00+line01+line02
                line1=[]
                y0=x0['main']
                for key in y0:
                    if key==Created_Date:
                        line1.append(line0.format(key,y0[key]['col1'],y0[key]['col2'],y0[key]['col3'],y0[key]['col4'],y0[key]['col5'],y0[key]['col6'],y0[key]['col7'],y0[key]['col8'],y0[key]['col9'],y0[key]['col10']))
                    else:
                        pass
                #return RedirectResponse(url='/login/who')
                #return {'hello':'world'}
                return HTMLResponse(content=html0.format(Title='修改项目',action='<form name="input" action=/'+tablename+'/modify method="get">',tables=''.join(line1),buttonname='修改',deletelink='',download1='',test='',addnewhere='',cols=colsx,add0='',del0='',logon_user=username))
            else:
                print("UIUIUIUIUIUIUIU")
                
                x0=readjson(json_file)
                log(tablename+' '+username+' '+'modify '+'before:'+str(x0['main'][Created_Date]))
                x0['main'][Created_Date]['col1']=col1
                x0['main'][Created_Date]['col2']=col2
                x0['main'][Created_Date]['col3']=col3
                x0['main'][Created_Date]['col4']=col4
                x0['main'][Created_Date]['col5']=col5
                x0['main'][Created_Date]['col6']=col6
                x0['main'][Created_Date]['col7']=col7
                x0['main'][Created_Date]['col8']=col8
                x0['main'][Created_Date]['col9']=col9
                x0['main'][Created_Date]['col10']=col10
                savejson(x0,json_file)
                log(tablename+' '+username+' '+'modify '+'after:'+str(x0['main'][Created_Date]))
                return RedirectResponse(url='/'+tablename)


def load_jsons():
    '''每次启动时，自动加载已有的json数据库文件'''
    for file in os.listdir('./jsons'):
        if file.endswith('.json'):
            tablenamex=file[:-5]
            
            json_file='./jsons/'+tablenamex+'.json'
            x0=readjson(json_file)
            #writejson(list1,json_file,table='cols')
            #x0=readjson(json_file)
            print('0000000000000000000000000000000')
            print('x0',x0)
            print("x0['cols']",x0['cols'])
            list2=x0['cols']
            for x in list2:
                list3=list2[x]
            Tables(tablenamex,list3)
load_jsons()
#load_jsons()

    
#hello0=Tables('hello0',["GD01","GD02","GD03"])
#hello1=Tables('action',['日期','时间','地点','人物','事件','详细内容'])
#hello2=Tables('hello2')
@app.post("/uploadfiles/")
async def create_upload_files(
    files: UploadFile = File(...)
):
    #return {"filenames": [file.filename for file in files]}
    #contents = await files[0].read().decode('utf8')
    contents = files.file.read()
    name0=files.filename
    with open('static/upload/'+name0,'wb') as f:
        f.write(contents)
    #return files[0].filename, files[0].content_type
        content = """
<body>
<a href="/static/upload/{}" title="转到CSS5主页">上传完成，下载链接请右键复制</a>
</body>
 """.format(name0)
    return HTMLResponse(content=content)


@app.get("/upload")
async def upload():
    content = """
<body>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
</body>
 """
    return HTMLResponse(content=content)